package me.sunsy.kit.proxy

import com.sun.xml.internal.fastinfoset.util.StringArray
import me.sunsy.kit.proxy.inter.MyInvocationTest
import me.sunsy.kit.proxy.inter.MyPlugin
import me.sunsy.kit.proxy.inter.MyPluginOne
import me.sunsy.kit.proxy.inter.Schedu
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy

class ScheduProxy : InvocationHandler {

    var obj: Any
    var interceptors: List<MyPlugin>
    var plugin: MyPlugin

    private constructor(obj: Any) : this(obj, ArrayList<MyPlugin>())


    private constructor(obj: Any, interceptors: List<MyPlugin>) : this(obj, interceptors, MyPluginOne())

    private constructor(obj: Any, interceptors: List<MyPlugin>, plugin: MyPlugin) {
        this.interceptors = interceptors
        this.obj = obj
        this.plugin = plugin
    }


    override fun invoke(proxy: Any, method: Method, args: Array<Any>): Any? {
        println("执行前干了一些事情")
        var myInvocation = MyInvocationTest(obj, method, args)
        return plugin.interceptor(myInvocation)
//        var object1 = method.invoke(obj, *args)
//        println("执行后干一些事情 ")
//        return object1
    }

    companion object {
        fun wrap(target: Any): Any {
            return Proxy.newProxyInstance(
                target.javaClass.classLoader,
                target.javaClass.interfaces,
                ScheduProxy(target)
            )
        }

        fun wrap(target: Any, interceptors: List<MyPlugin>): Any {
            return Proxy.newProxyInstance(
                target.javaClass.classLoader,
                target.javaClass.interfaces,
                ScheduProxy(target, interceptors)
            )
        }

        fun wrap(target: Any, interceptors: List<MyPlugin>, plugin: MyPlugin): Any {
            return Proxy.newProxyInstance(
                target.javaClass.classLoader,
                target.javaClass.interfaces,
                ScheduProxy(target, interceptors, plugin)
            )
        }
    }
}